package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.BusinessException;
import com.itheima.ydd.common.PageResult;
import com.itheima.ydd.common.ResultData;
import com.itheima.ydd.common.UserHolder;
import com.itheima.ydd.dto.ArticleDto;
import com.itheima.ydd.dto.BaseInfoDto;
import com.itheima.ydd.dto.CateDto;
import com.itheima.ydd.dto.UserDto;
import com.itheima.ydd.entity.*;
import com.itheima.ydd.service.*;
import com.itheima.ydd.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static net.sf.jsqlparser.parser.feature.Feature.limit;

/**
 * 后台管理
 */
@RestController
@Slf4j
@RequestMapping("index")
public class IndexController {

    @Autowired
    private UserService userService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private AdvposService advposService;

    @Autowired
    private TagService tagService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CateService cateService;

    @Autowired
    private AdvimgService advimgService;

    @Autowired
    private YddUserService yddUserService;

    /**
     * 用户登录
     *
     * @param user
     * @return
     */
    @PostMapping("login")
    public ResultData login(@RequestBody User user) {
        log.info("用户信息: 邮箱:{},密码:{}", user.toString());

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getLogin_name, user.getLogin_name());
        queryWrapper.eq(User::getPassword, DigestUtils.md5Hex(user.getPassword()));
        User loginUser = userService.getOne(queryWrapper);

        if (loginUser == null) {
            throw new BusinessException("登录失败!");
        }

        Map retMap = new HashMap();
        Map tokenMap = new HashMap<>();
        // 登录成功
        if (loginUser != null) {
            // 生成token信息
            String roleId = loginUser.getRole_id()
                    .replace("[", "")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("id", loginUser.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);

        }
        return ResultData.ok("", retMap);
    }


    /**
     * 获取系统配置
     *
     * @return
     */
    @GetMapping("getConfig")
    public ResultData getConfig() {
        List<Config> list = configService.list();

        Map<String, String> map = new HashMap<>();
        for (Config config : list) {
            map.put(config.getAttr_key(), config.getAttr_value());
        }
        return ResultData.ok("", map);
    }

    /**
     * 获取用户资料
     *
     * @param
     * @return
     */
    @PostMapping("profile")
    public ResultData profile() {
        Map<String, Object> map = configService.profile();
        return ResultData.ok("", map);
    }


    @PostMapping("/logout")
    public void logout() {
        //删除用户信息
        UserHolder.remove();
    }

    @GetMapping("/baseInfo")
    public ResultData baseInfo() {

        BaseInfoDto baseInfoDto = new BaseInfoDto();
        List<Cate> cates = cateService.list();
        List<CateDto> cateDtos = cates.stream().map(cate -> {
            CateDto cateDto = new CateDto();
            BeanUtils.copyProperties(cate, cateDto);
            LambdaQueryWrapper<Article> lqw = new LambdaQueryWrapper<>();
            lqw.eq(Article::getCateid, cate.getId());
            int count = articleService.count(lqw);
            cateDto.setNum(count);
            return cateDto;
        }).collect(Collectors.toList());
        //广告位总数
        baseInfoDto.setAdvposNum(advposService.count());
        //标签总数
        baseInfoDto.setTagNum(tagService.count());
        //管理员总数
        baseInfoDto.setAdminNum(userService.count());
        //文章总数
        baseInfoDto.setArticleNum(articleService.count());
        //分类总数
        baseInfoDto.setCateNum(cateService.count());
        //广告图总数
        baseInfoDto.setAdvimgNum(advimgService.count());
        baseInfoDto.setAllCateList(cateDtos);

        LambdaQueryWrapper<YddUser> yddUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        yddUserLambdaQueryWrapper.select(YddUser::getId, YddUser::getUsername, YddUser::getSex, YddUser::getIcon, YddUser::getAddress);
        yddUserLambdaQueryWrapper.orderByDesc(YddUser::getId);
        yddUserLambdaQueryWrapper.last("limit 7");
        List<YddUser> yddUsers = yddUserService.list(yddUserLambdaQueryWrapper);
        baseInfoDto.setNewUserList(yddUsers);

        LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleLambdaQueryWrapper.select(Article::getId, Article::getTitle, Article::getAuthor, Article::getKeywords, Article::getKeywords);
        articleLambdaQueryWrapper.orderByDesc(Article::getClick);
        articleLambdaQueryWrapper.last("limit 7");
        List<Article> articleList = articleService.list(articleLambdaQueryWrapper);
        baseInfoDto.setHotArticleList(articleList);


        //用户总数
        LambdaQueryWrapper<YddUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(YddUser::getSex, 0);
        int manCount = yddUserService.count(lambdaQueryWrapper);
        int total = yddUserService.count();
        int womanCount = total - manCount;
        UserDto userDto = new UserDto();
        userDto.setTotal(total);
        userDto.setUserMan(manCount);
        userDto.setUserWoman(womanCount);
        baseInfoDto.setUser(userDto);

        return ResultData.ok("查询成功", baseInfoDto);
    }


}

